<template>
  <div style="width: 1000px; margin: auto">
    <el-alert
      title="温馨提示：平台及销售商不会以任何理由，要求您点击任何网址链接进行退款或支付操作。"
      type="warning"
      show-icon
      :closable="false"
      style="margin-top: 20px"
    >
    </el-alert>
    <div>
      <el-row>
        <h1>收件人信息</h1>
      </el-row>
      <el-row>
        <div class="adressList">
          <ul>
            <li v-for="(item, index) in addressInfo" :key="item.id">
              <el-card
                shadow="hover"
                @click.native="clickAddress(item, index)"
                :class="{ clickOne: selectIndex == index }"
              >
                <div slot="header" class="clearfix">
                  <span>{{ item.recipients }}</span>
                  <span style="float: right; padding: 3px 0">
                    {{ item.telephone }}
                  </span>
                </div>
                <span>
                  {{ item.address }}
                </span>
                <div class="conlink">
                  <span>
                    <a href="#" @click="editAddress(item, index)">编辑</a>
                    <a href="#" @click="deleteAddress(item, index)">删除</a>
                  </span>
                </div>
              </el-card>
            </li>
          </ul>
        </div>
      </el-row>
      <el-row>
        <el-button @click="addAddress">新增收货地址+</el-button>
      </el-row>
    </div>
    <div>
      <el-row>
        <h1>支付方式</h1>
      </el-row>
      <el-row>
        <ul>
          <li v-for="(item, index) in payInfo" :key="item.id">
            <el-card
              shadow="hover"
              @click.native="clickpay(item, index)"
              :class="{ clickPay: selectpayIndex == index }"
            >
              <img
                :src="localhostPath + item.paymentPicturePath"
                alt=""
                style="width: 50px; height: 50px; vertical-align: middle"
              />

              <span>
                {{ item.modeOfPayment }}
              </span>
            </el-card>
          </li>
        </ul>
      </el-row>
    </div>
    <div class="newsubmit">
      <div class="jisong">
        <div class="jisong_text">寄送至：</div>
        <div class="jisong_addree">
          {{ this.selectAddress.address }}<br />
          {{ this.selectAddress.recipients }}{{ this.selectAddress.telephone }}
        </div>
        <!---->
      </div>

      <div class="newbox tip_tuan">
        <div class="newbox_text">
          共<span class="red">{{totalNumber}}</span
          >件商品
          <span class="price">
            <b>
              实付：
              <span style="color: #ff2832">¥</span>
              <span class="red">{{totalPrice}}</span>
            </b>
          </span>
        </div>
        <div class="btn_red">
          <a
            id="submit"
            href="javascript:void(0)"
            style="color: #fff"
            @click="goPay"
            >去支付</a
          >
        </div>
      </div>
    </div>

    <el-dialog title="收货地址信息" :visible.sync="dialogVisible" width="500px">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item
          label="收件人"
          :label-width="formLabelWidth"
          prop="recipients"
        >
          <el-input v-model="form.recipients" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="收件人电话"
          :label-width="formLabelWidth"
          prop="telephone"
        >
          <el-input
            v-model="form.telephone"
            autocomplete="off"
            maxlength="11"
            show-word-limit
            oninput="value=value.replace(/[^\d]/g,'')"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="省市区/县"
          prop="address1"
          :label-width="formLabelWidth"
        >
          <el-cascader
            :options="cityData"
            v-model="form.address1"
          ></el-cascader>
        </el-form-item>
        <el-form-item
          label="详细地址"
          :label-width="formLabelWidth"
          prop="address2"
        >
          <el-input v-model="form.address2" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm('form')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAddress,
  deleteAddress,
  editAddress,
  addAddress,
  getPay,
} from "../api/address";
import { addOrder, isPay } from "../api/order";
import cityData from "../util/citydata";
import common from "../util/common";

export default {
  data() {
    return {
      localhostPath: common.localhostPath,
      cityData,
      dialogVisible: false,
      formLabelWidth: "120px",
      addressInfo: [],
      selectIndex: -1,
      selectpayIndex: -1,
      payInfo: [],
      selectAddress: {},
      form: {
        id: 0,
        recipients: "",
        address: "",
        telephone: "",
        address1: "",
        address2: "",
      },
      rules: {
        recipients: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        telephone: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { max: 11, message: "填写正确的联系电话" },
          { min: 11, message: "填写正确的联系电话" },
        ],
        address1: [{ required: true, message: "请输入地址", trigger: "blur" }],
        address2: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
      },
      newIndex: 0,
      multipleSelection: {},
      orderForm: {
        // 用户ID
        userId: Number(localStorage.getItem("userId")),
        // 商品Id
        selectCommodity: [],
        // 收获信息Id
        receivingId: 0,
        // 支付方法Id
        paymentId: 0,
      },
      orderNumberForm:{
        orderNumber:""
      }
    };
  },
  methods: {
    clickAddress(row, index) {
      this.selectIndex = index;
      this.selectAddress = row;
      this.orderForm.receivingId = row.id;
    },
    clickpay(row, index) {
      this.orderForm.paymentId = row.id;
      this.selectpayIndex = index;
    },
    // 添加框
    addAddress() {
      this.dialogVisible = true;
      this.form = {};
    },
    //编辑
    editAddress(item, index) {
      this.form.id = item.id;
      this.form.recipients = item.recipients;
      this.form.telephone = item.telephone;
      this.form.address1 = item.address1;
      this.form.address2 = item.address2;
      this.newIndex = index;
      this.dialogVisible = true;
    },
    // 删除
    deleteAddress(item, index) {
      this.$confirm("此操作将永久删除该收获地址, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteAddress(item.id)
          .then(({ data }) => {
            this.addressInfo.splice(index, 1);
            console.log(data);
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      });
    },
    confirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.form.id == undefined) {
            this.form.address =
              this.form.address1.join("") + this.form.address2;
            var id = localStorage.getItem("userId");
            addAddress(id, this.form).then(({ data }) => {
              this.addressInfo.push(data.data);
              this.dialogVisible = false;
            });
          } else {
            this.form.address =
              this.form.address1.join("") + this.form.address2;
            editAddress(this.form.id, this.form).then(({ data }) => {
              this.addressInfo.splice(this.newIndex, 1, data.data);
              this.dialogVisible = false;
            });
          }
        } else {
          this.$message.error("请填写完整");
        }
      });
    },
    getMun() {
      var arr = JSON.parse(localStorage.getItem("multipleSelection"));
      let result = arr.reduce(
        (p, c) => {
          Object.keys(p).forEach((k) => (p[k] += c[k]));
         
          return p;
        },
        { price: 0, inventory: 0 }
      );
      this.multipleSelection = result;
    },
    goPay() {
      var arr = [];
      var commodity = JSON.parse(localStorage.getItem("multipleSelection"));
      commodity.map((item) => {
        arr.push(item);
      });
      this.orderForm.selectCommodity = arr;
      addOrder(this.orderForm).then(({ data }) => {
        console.log(data);
        this.$confirm("请确定支付", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
          .then(() => {
            this.orderNumberForm.orderNumber = data.data;
            isPay(this.orderNumberForm).then(({ data }) => {
              console.log(data);
              this.$router.push("/PayGood");
            });
            this.$message({
              type: "success",
              message: "支付成功",
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消支付",
            });
            this.$router.push("/PayGood");
          });
      });
    },
  },
  mounted() {
    var id = localStorage.getItem("userId");
    getAddress(id).then(({ data }) => {
      this.addressInfo = data.data;
    });
    getPay().then(({ data }) => {
      this.payInfo = data.data;
    });
    this.getMun();
  },
  computed: {
    // 总价
    totalPrice() {
      var commodity = JSON.parse(localStorage.getItem("multipleSelection"));
      var price_total = 0;
      for (var i = 0; i < commodity.length; i++) {
        price_total +=
          commodity[i].price * commodity[i].inventory;
      }
      return price_total;
    },
    // 总数
    totalNumber() {
      var commodity = JSON.parse(localStorage.getItem("multipleSelection"));
      var number_total = 0;
      for (var i = 0; i < commodity.length; i++) {
        number_total += commodity[i].inventory;
      }
      return number_total;
    },
  },
};
</script>

<style scoped>
ul li {
  float: left;
  margin-right: 30px;
}

.adressList .el-card {
  width: 250px;
  height: 210px;
}

.clickOne {
  width: 250px;
  border: 1px solid red;
}
.conlink {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
.conlink a {
  padding-left: 10px;
}
.clickPay {
  border: 1px solid red;
}

.newsubmit {
  width: 960px;
  height: 70px;
  margin: 0 auto;
  background: #f1f5f8;
}
.newsubmit .jisong {
  height: 60px;
  width: 450px;
  float: left;
  padding-top: 10px;
}
.newsubmit .jisong_text {
  float: left;
  height: 38px;
  padding-top: 4px;
  margin-left: 15px;
  color: #000000;
  font-family: MicrosoftYaHei;
  line-height: 1.4;
}
.newsubmit .jisong_addree {
  font-family: MicrosoftYaHei;
  color: #656565;
  letter-spacing: 0;
  text-align: justify;
  line-height: 24px;
}
.newsubmit .newbox.tip_tuan {
  height: 70px;
  position: relative;
}
.newsubmit .newbox {
  width: 500px;
  text-align: right;
  color: #646464;
  height: 36px;
  float: right;
}
.newsubmit .newbox .newbox_text {
  height: 60px;
  width: 335px;
  float: left;
  padding-top: 10px;
}
.newsubmit .newbox .btn_red {
  height: 70px;
  width: 140px;
  line-height: 70px;
  text-align: center;
  color: #fff;
  float: right;
  background-color: #ff2832;
  font-size: 16px;
  margin-left: 20px;
  border-radius: 0px;
  font-weight: bold;
}
</style>